package com.ch999.mobileoa;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ch999.mobileoa.data.SearchData;
import com.ch999.mobileoa.page.FloatCustomActivity;
import com.ch999.mobileoa.page.LoginActivity;
import com.ch999.mobileoa.page.ScanActivity;
import com.ch999.mobileoa.request.DataControl;
import com.ch999.mobileoa.util.Location;
import com.joanzapata.android.BaseAdapterHelper;
import com.sda.lib.HttpCore.DataResponse;
import com.sda.lib.util.Logs;
import com.sda.lib.util.Tools;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;

import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {


    @ViewInject(id = R.id.textView)
    TextView textView;
    @ViewInject(id = R.id.image)
    ImageView imageView;
    Context context;
    @ViewInject(id = R.id.home_search)
    AutoCompleteTextView home_search;
    @ViewInject(id = R.id.toolbar)
    Toolbar toolbar;
    @ViewInject(id = R.id.search_area)
    LinearLayout search_area;
    @ViewInject(id = R.id.drawer_layout)
    DrawerLayout drawer;
    @ViewInject(id =R.id.home_search_listview)
    ListView search_list ;

    ActionBarDrawerToggle toggle;

    SearchAdapter searchAdapter ;

    List<SearchData> searchDataList = new ArrayList<SearchData>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        FinalActivity.initInjectedView(this);
        context = HomeActivity.this;
        setSupportActionBar(toolbar);

        setUp();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initLocation();
    }

    private void initLocation() {
        Location location = new Location(getApplicationContext());
        location.getGPS();
    }

    private void setUp() {
        //floatButton
        final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
                Intent intent = new Intent(HomeActivity.this, FloatCustomActivity.class);
                ActivityOptionsCompat optionsCompat =
                        ActivityOptionsCompat.makeSceneTransitionAnimation(HomeActivity.this, fab, getString(R.string.float_str));
                ActivityCompat.startActivity(HomeActivity.this, intent, optionsCompat.toBundle());
            }
        });


        toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);



        //搜索框
        home_search.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    search_area.setVisibility(View.VISIBLE);
                    ValueAnimator anim = ValueAnimator.ofFloat(0, 1f);
                    anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator valueAnimator) {
                            float slideOffset = (Float) valueAnimator.getAnimatedValue();
                            toggle.onDrawerSlide(drawer, slideOffset);
                        }
                    });
                    anim.setInterpolator(new DecelerateInterpolator());
                    anim.setDuration(300);
                    anim.start();
                } else {
                    search_area.setVisibility(View.GONE);
                    ValueAnimator anim = ValueAnimator.ofFloat(1f, 0);
                    anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator valueAnimator) {
                            float slideOffset = (Float) valueAnimator.getAnimatedValue();
                            toggle.onDrawerSlide(drawer, slideOffset);
                        }
                    });
                    anim.setInterpolator(new DecelerateInterpolator());
                    anim.setDuration(300);
                    anim.start();
                }
            }
        });


        // 搜索结果列表
        searchAdapter = new SearchAdapter();
        search_list.setAdapter(searchAdapter);

        home_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 执行请求
                FuzzyQuery(s.toString());
                if (count==0){
                    searchDataList.clear();
                    searchAdapter.notifyDataSetChanged();
                    search_list.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,0));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (Tools.isEmpty(s.toString())){
                    searchDataList.clear();
                    searchAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    /**
     * 快速搜索
     * @param s
     */
    private void FuzzyQuery(String s) {
        DataControl.FuzzyQuery(context, s, new DataResponse() {
            @Override
            public void onSucc(Object response) {
                searchDataList.clear();
                searchDataList = (List<SearchData>) response;
                searchAdapter.notifyDataSetChanged();

                search_list.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,searchDataList.size() * Tools.dip2px(context,50)));
            }

            @Override
            public void onFail(String error) {

            }
        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (search_area.isShown()) {
                toolbar.setSelected(true);
                toolbar.setFocusable(true);
                toolbar.setFocusableInTouchMode(true);
                toolbar.requestFocus();
            }else{
                finish();
            }
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        Logs.Debug("onBackPressed");
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        switch (id) {
            case R.id.item_nav_1:
                startActivity(new Intent(context, ScanActivity.class));
                break;
            case R.id.item_nav_2:
                startActivity(new Intent(context, LoginActivity.class));
                break;
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private class SearchAdapter extends BaseAdapter{
        @Override
        public int getCount() {
            return searchDataList.size();
        }

        @Override
        public Object getItem(int position) {
            return searchDataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            SearchData data  = searchDataList.get(position);
            Logs.Debug("Data==="+data.getName());
            BaseAdapterHelper helper = BaseAdapterHelper.get(context,convertView,parent,R.layout.listview_style_for_search);
            helper.setText(R.id.content,data.getName());
            return helper.getView();
        }
    }
}
